<?php

class LoginControl extends Control {
	const USERNAME = '_OXYGEN_USERNAME';
	const PASSWORD = '_OXYGEN_PASSWORD';
	
	private $redirect_on_success;
	public function WithRedirectOnSuccess($value){ $this->redirect_on_success = $value; return $this; }
	
	private $message;
	public function WithMessage($value){ $this->message = $value; return $this; }

	public function Render(){
		$Username = '';

		$v = new ValidatorSet();
		if (Oxygen::IsPostback()) {
			$Username = Http::$POST[self::USERNAME]->AsString();
			$v->Username->CheckMandatory($Username);
			$Password = Http::$POST[self::PASSWORD]->AsString();
			$v->Password->CheckMandatory($Password);
			if ($v->HasPassed()){
				$u = User::RetrieveByUsername($Username);
				$v->Username->Check($u!=null,new ErrorMessage(Lemma::ErrorInvalidUsername()));
				if ($v->HasPassed()) {
					$v->Password->Check($u->Password == Oxygen::Hash($Password),new ErrorMessage(Lemma::ErrorInvalidPassword()));
					if ($v->HasPassed()){
						User::Login($Username,$Password);
						Oxygen::Redirect($this->redirect_on_success);
					}
				}
			}
		}
		
		
		echo '<br/>';
		echo Oxygen::GetAction()->GetForm();
		$z = FieldTableControl::Make()->WithLabelWidth('10px');
		if ($this->message != null) $z->Add('')->Write($this->message);
		$z->Add(Lemma::Username())->Write(TextboxControl::Make(self::USERNAME,$Username)->WithWidth('250px'))->WithValidator($v->Username);
		$z->Add(Lemma::Password())->Write(PasswordControl::Make(self::PASSWORD)->WithWidth('250px'))->WithValidator($v->Password);
		$z->Add('')->Write(ButtonControl::Make()->WithIsSubmit(true)->WithValue(Lemma::Login()));
		$z->Render();
		echo Oxygen::GetAction()->EndForm();

	}
}


?>
